var mongoose = require('mongoose');
var Carts = require('../models/carts.model')// 引数据模型
var path=require('path');
var Product = require('../models/product.model')
var async = require('async')


// 新增
exports.create = function(req,res,next){
    console.log(req.body)
    var body = {userId:req.body.userId,productId:req.body.productId};
    const carts = new Carts(req.body);
    Carts.find(body).then(response=>{
        if(response.length>0){
            console.log('有找到')
            Carts.findOneAndUpdate(body,{$set: req.body}, {new:false} )
            .then(data=>{
                res.json({msg:'数据修改成功',status:200});
            })
        }else{
            carts.save().then(res=>{
                res.json({msg:'数据添加成功',status:200})
            })
        }
    })
}


//删除
exports.remove = function(req,res,next){
    var body = {userId:req.body.userId,productId:req.body.productId};
    Carts.Remove(body,function(err,doc){
        res.json({msg:'数据删除成功',status:200})
    })

} 


exports.list = function(req,res,next){
    var page = (req.body.page) ? req.body.page : 1;
    var limit = (req.body.limit) ? req.body.limit : 8;

    Carts.find({userId:req.body.userId}).then(response=>{
        if(response.length>0){
            var queryCondition = {};
            var userId;
            userId = req.body.userId;
            queryCondition = {userId:userId}


            Carts.paginate(queryCondition, { page: page, limit: limit }, function(err, result) {
                
                    async.map(result.docs,function(user,callback){
                        Product.find({_id:user.productId}).then(data=>{
                            data[0].quantity = user.productNum;
                            // console.log(user.quantity)
                            callback(null,data[0])
                        })
                    },function(err,results){
                        // console.log(results)
                        result.rows = results;
                        delete result.docs;
                        res.json(result)
                    })
            });
            
        }else{
            res.json({msg:'没有找到该用户的数据',status:200})
        }
    })

}